<template>
  <el-dialog v-model="props.addVisible" title="添加生产任务" width="55%" :before-close="handleClose"
    class="production-task-dialog" append-to-body>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <!-- Workstation -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="工作站" prop="workstationName" required>
            <el-input v-model="form.workstationName" readonly placeholder="请选择工作站" style="width: 180px;">
              <template #append>
                <el-button @click="selectedRank">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甘特图显示颜色" label-width="180px" prop="color" required>
            <el-color-picker v-model="form.colorCode" class="ml-2" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-input v-model="form.colorCode" readonly placeholder="请选择颜色" style="width: 150px;" />
        </el-col>
      </el-row>

      <!-- Production Quantity -->
      <el-form-item label="排产数量" prop="quantity" required>
        <el-input-number v-model="form.quantity" :min="0" :max="props.form.quantity" class="w-32" />
      </el-form-item>

      <!-- Start Time -->
      <el-row>
        <el-col :span="8">

          <el-form-item label="开始时间" prop="startTime" required>
            <el-date-picker v-model="form.startTime" type="datetime" placeholder="请选择开始生产时间" class="w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产时长" prop="duration" required>
            <el-input-number v-model="form.duration" :min="1" class="w-32" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="完成时间">
            <el-date-picker v-model="completionTime" disabled type="datetime" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
    <select-workstation :dialogVisible="dialogVisible" :processCode="props.processCode" @data-return="workData"
      @close="CloseSelect" />
  </el-dialog>
</template>

<script setup>
import { computed, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import SelectWorkstation from "@/components/ProductionScheduling/SelectWorkstation.vue";
import { getPageUnits } from "@/apis/zyj/units.js";
import { insertTask } from "@/apis/zyj/ProductionSceduling.js";
import { ElMessage } from "element-plus";

const props = defineProps({
  addVisible: Boolean,
  processCode: String,
  form: Object,
  procedureCode: String
})
const emit = defineEmits(['close'])
const formRef = ref(null)
const dialogVisible = ref(false)

const form = ref({
  workstationName: '',
  quantity: 1,
  startTime: '',
  duration: 1,
  colorCode: '#00AEF3'
})

const resetForm = ref({ ...form.value });

function createID() {
  let code = 'TASK';
  let date = new Date();
  let year = date.getFullYear();
  code = code + year + Math.floor(Math.random() * 10000);
  return code;
}

const rules = {
  workstationName: [
    { required: true, message: '请选择工作站', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入排产数量', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入生产时长', trigger: 'blur' }
  ]
}

const completionTime = computed(() => {
  if (!form.value.startTime) return ''
  const date = new Date(form.value.startTime)
  date.setHours(date.getHours() + form.value.duration)

  // 自定义格式化函数
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  return formatDate(date);
})

// 自定义格式化函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const selectedRank = () => {
  dialogVisible.value = true
}

const CloseSelect = () => {
  dialogVisible.value = false
}
const workData = (row) => {
  console.log(row)
  form.value.workstationName = row.workstationName
  form.value.workstationCode = row.workstationCode
  form.value.workstationId = row.workstationId
  form.value.processCode = row.processCode
  form.value.processName = row.process.processName

}

const handleClose = () => {
  Object.assign(form, resetForm)
  emit('close')
}

const handleSubmit = async () => {

  console.log(props.form, props.form.unitOfMeasure)
  let unitList = await getPageUnits(props.form.unitOfMeasure, '', '-1', '-1');
  let rwn = '个'
  if (unitList.length > 0) {
    rwn = unitList[0].unitName
  }
  form.value.taskName = props.form.productName + "【" + props.form.quantity + "】" + rwn

  form.value.taskCode = createID()
  form.value.workorderId = props.form.workorderId
  form.value.workorderCode = props.form.workorderCode
  form.value.workorderName = props.form.workorderName
  form.value.routeCode = props.procedureCode
  form.value.itemId = props.form.productId
  form.value.itemCode = props.form.productCode
  form.value.itemName = props.form.productName
  form.value.specification = props.form.productSpc
  form.value.unitOfMeasure = rwn
  form.value.quantityProduced = 0
  form.value.clientId = props.form.clientId
  form.value.clientCode = props.form.clientCode
  form.value.clientName = props.form.clientName
  form.value.requestDate = props.form.requestDate
  form.value.quantityQuanlify = 0
  form.value.quantityUnquanlify = 0
  form.value.quantityChanged = 0
  let a = completionTime
  form.value.endTime = a.value
  console.log(form.value)
  await insertTask(form.value).then(res => {
    if (res == "成功") {
      ElMessage.success('添加成功!')
      form.value = {
        workstationName: '',
        quantity: 1,
        startTime: '',
        duration: 1,
        colorCode: '#00AEF3'
      }
      handleClose()
    } else ElMessage.error("添加失败！")
  })
}
</script>

<style scoped>
.production-task-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>